using System;
using System.Collections.Generic;
using System.Linq;
using Domain.Model.Addresses;
using Domain.Model.Partners;
using Infrastructure.Data;

namespace Application.Services.PartnersManagement
{
    public class PartnersManagementService : IPartnersManagementService
    {
        private readonly IMainModuleUnitOfWork _unitOfWork;

        public PartnersManagementService(IMainModuleUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        #region Implementation of IPartnerManagementService 

        public List<Partner> GetAllPartners()
        {
            return _unitOfWork.Partners.ToList();
        }

        public Partner FindPartnerByCode(int partnerCode)
        {
            return (from partner in _unitOfWork.Partners
                    where partner.Code == partnerCode
                    select partner).SingleOrDefault();
        }

        public Partner CreateNewPartner()
        {
            var partner = new Partner { Code = 1 };
            partner.Code += _unitOfWork.Partners.Max(c => c.Code);
            return partner;
        }

        public bool SavePartner(Partner partner)
        {
            // Add Partner to Partners repository
            _unitOfWork.Partners.Add(partner);

            // Commit changes
            return _unitOfWork.SaveChanges() == 1 ? true : false;
        }

        public bool DeletePartner(Partner partner)
        {
            // Remove Partner from Partners repository
            _unitOfWork.Partners.Remove(partner);

            // Commit changes
            return _unitOfWork.SaveChanges() == 1 ? true : false;
        }

        public Address GetPartnerMainAddress(Partner partner)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}